#include "nvs_flash.h"
#include <stdio.h>
#include "nvs.h"
#include "esp_system.h"
#include "esp_log.h"

#include "app_nvs_param.h"
#include "audio_mem.h"
#include "string.h"

#define STORAGE_NAMESPACE "device_param"

static const char *TAG = "app.music";
/*
1、initialise nvs flash component.
2、load device param to struct.
3、The specified device parameters can be obtained by obtaining the structure members.
4、If device parameters are updated, you need to save the updated data to nvs.

system param define 
User unmodifiable:example factory load in
system param

User modifiable:
mqtt param{
    url
    username
    password
}
*/


esp_err_t app_get_mqtt_param(mqtt_nvs_param_t param_mqtt)
{
    nvs_handle_t my_handle;
    esp_err_t err;
    size_t size;
    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) return err;
    memset(param_mqtt, 0, sizeof(mqtt_nvs_param));
    // obtain required memory space to store blob being read from NVS
    err = nvs_get_blob(my_handle, "param_mqtt", param_mqtt, &size);
    if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) return err;
    ESP_LOGI(TAG, "------------------------");
    ESP_LOGI(TAG, "GET param_mqtt info:");
    ESP_LOGI(TAG, "url:%s", param_mqtt->url);
    ESP_LOGI(TAG, "username:%s", param_mqtt->username);
    ESP_LOGI(TAG, "password:%s", param_mqtt->password);
    ESP_LOGI(TAG, "------------------------");
    // Close
    nvs_close(my_handle);
    return ESP_OK;
}

esp_err_t app_set_mqtt_param(mqtt_nvs_param_t data)
{
    nvs_handle_t my_handle;
    esp_err_t err;
    size_t size;
    mqtt_nvs_param_t param_mqtt = data;

    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);

    if (err != ESP_OK) return err;

    err = nvs_set_blob(my_handle, "param_mqtt", param_mqtt, sizeof(mqtt_nvs_param));

    if (err != ESP_OK) return err;

    // Commit
    err = nvs_commit(my_handle);
    if (err != ESP_OK) return err;

    nvs_close(my_handle);

    ESP_LOGI(TAG, "set mqtt nvs successfully.");

    return ESP_OK;
}
